<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->

          <basic-information :info="formInfo"></basic-information>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button @click="addProduct">新增行</el-button>
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除行</el-button
              >
            </template>
          </page-filter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <page-table
                ref="table"
                :class="{
                  isShow:
                    selectProductInfo.popoVisible ||
                    selectBatchInfo.popoVisible,
                }"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :spanMethod="spanMethod"
                :tabIndex="false"
                :check-box="true"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :cell-class-name="tableCellClassName"
                :isDynamic="true"
                methodKey="groupKey"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-commonName="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType && scope.row.emptyRowType === '1'
                    "
                    :ref="'productRef' + scope.$index"
                    :class="'productKey' + scope.$index"
                    class="productKey"
                    placeholder="名称\编码\规格\批号"
                    v-model="scope.row.productKeyword"
                    @keyup.enter="productSearchInput(scope.row, scope.$index)"
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="productSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <span v-else>{{ scope.row.commonName }}</span>
                </template>
                <template v-slot:col-price="scope">{{
                  scope.row.emptyRowType && scope.row.emptyRowType === '1'
                    ? ''
                    : $fn.TripartiteMethod(scope.row.price)
                }}</template>
                <template v-slot:col-pendDownSelfQty="scope">{{
                  scope.row.emptyRowType && scope.row.emptyRowType === '1'
                    ? ''
                    : $fn.qtyFormatter(scope.row.pendDownSelfQty)
                }}</template>
                <template v-slot:col-goodsLocationNo="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType &&
                      (scope.row.emptyRowType === '1' ||
                        scope.row.emptyRowType === '2') &&
                      (!scope.row.codeType ||
                        scope.row.codeType === 1 ||
                        scope.row.codeType === 4)
                    "
                    :ref="'batchRef' + scope.$index"
                    :class="'batchKey' + scope.$index"
                    class="batchKey"
                    placeholder="货位编码"
                    :disabled="!scope.row.groupKey"
                    v-model="scope.row.batchKeyword"
                    @keyup.enter="
                      batchNumberSearchInput(scope.row, scope.$index)
                    "
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="batchNumberSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <span v-else>{{ scope.row.goodsLocationNo || '-' }}</span>
                </template>
                <template v-slot:col-storeBatchNumber="scope">
                  <StoreBatchNumberTag :row="scope.row" />
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item
                    class="margin-bottom"
                    v-if="
                      (scope.row.codeType === 1 || scope.row.codeType === 4) &&
                      !scope.row.emptyRowType
                    "
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div> -->
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                              @change="
                                changeSmall(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.smallUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div> -->
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span
                    v-else-if="
                      (scope.row.codeType === 2 || scope.row.codeType === 3) &&
                      !scope.row.emptyRowType
                    "
                    >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                  >
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <SelectProduct
      v-if="selectProductInfo.visible"
      v-model:showDialog="selectProductInfo.visible"
      :tableKey="selectProductInfo.tableKey"
      :query="selectProductInfo.query"
      :highlightRow="false"
      :checkBox="true"
      :api="selectProductInfo.api"
      :showPrice="$permission('downShelfTask:price')"
      @callback="selectProductBackList"
    />
    <SelectBatch
      v-if="selectBatchInfo.visible"
      v-model:showDialog="selectBatchInfo.visible"
      :popoVisible="selectBatchInfo.visible"
      :tableKey="selectBatchInfo.tableKey"
      :query="selectBatchInfo.query"
      :codeType="selectBatchInfo.row.codeType"
      :api="selectBatchInfo.api"
      :highlightRow="false"
      :checkBox="true"
      :showPrice="$permission('downShelfTask:price')"
      @callback="selectBatchBackList"
    ></SelectBatch>
    <el-popover
      v-if="selectProductInfo.popoVisible"
      ref="productPopoverRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      :virtual-ref="productRef"
      width="1000px"
      :visible="selectProductInfo.popoVisible"
      virtual-triggering
      @hide="productPopoHide"
    >
      <ProductTable
        v-if="selectProductInfo.popoVisible"
        :popoVisible="selectProductInfo.popoVisible"
        :tableKey="selectProductInfo.tableKey"
        :query="selectProductInfo.query"
        :highlightRow="selectProductInfo.highlightRow"
        :checkBox="selectProductInfo.checkBox"
        :api="selectProductInfo.api"
        :refresh="selectProductInfo.refresh"
        :showPrice="$permission('downShelfTask:price')"
        tableType="product"
        @checkMore="checkMore('product')"
        @reset="selectProductInfo.popoVisible = false"
        @callback="selectProductBack"
        @keyDown="productKeyDown"
      ></ProductTable>
    </el-popover>
    <el-popover
      v-if="selectBatchInfo.popoVisible"
      ref="batchPopoverRef"
      :virtual-ref="batchRef"
      popper-class="popover-wrapper"
      placement="bottom-start"
      width="600px"
      :visible="selectBatchInfo.popoVisible"
      virtual-triggering
      @hide="batchPopoHide"
    >
      <ProductTable
        v-if="selectBatchInfo.popoVisible"
        :popoVisible="selectBatchInfo.popoVisible"
        :tableKey="selectBatchInfo.tableKey"
        :query="selectBatchInfo.query"
        :highlightRow="selectBatchInfo.highlightRow"
        :checkBox="selectBatchInfo.checkBox"
        :refresh="selectBatchInfo.refresh"
        :api="selectBatchInfo.api"
        :showPrice="$permission('downShelfTask:price')"
        :codeType="selectBatchInfo.row.codeType"
        tableType="batch"
        @checkMore="checkMore('batch')"
        @reset="selectBatchInfo.popoVisible = false"
        @callback="selectBatchBack"
        @keyDown="batchKeyDown"
      ></ProductTable>
    </el-popover>
    <BatchIndividual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      :leftApi="individualInfo.leftApi"
      :rightApi="individualInfo.rightApi"
      :leftTableKey="individualInfo.leftTableKey"
      :rightTableKey="individualInfo.rightTableKey"
      :leftQuery="individualInfo.leftQuery"
      :rightQuery="individualInfo.rightQuery"
      :details="individualInfo.details"
      :info="individualInfo.row"
      :_key="'goodsLocationId'"
      :changeLocationNo="true"
      :isRequest="individualInfo.isRequest"
      :isGetRightList="false"
      :showPrice="$permission('downShelfTask:price')"
      @callback="individualCallback"
    ></BatchIndividual>
  </div>
</template>
<script setup name="downShelfTaskModify">
import SelectProduct from '../components/SelectProduct'
import SelectBatch from '../components/SelectBatch'
import BatchIndividual from '../components/BatchIndividual'
import ProductTable from '../components/ProductTable'
import StoreBatchNumberTag from '@/views/stock/components/StoreBatchNumberTag'
import {
  downShelfSave,
  getDownShelfById,
  getDownShelfTaskDetailCustomizeListAll,
  getDownShelfTaskDetailCustomizeListPage,
  getDownShelfTaskDetailExtCustomizeListAll,
  getDepotStockCustomizeListPage,
} from '@/api/wms'
import { getCustomizeSetting } from '@/api/customize'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
import { setVal, setTabindex } from '@/common/js/base'
import _ from 'lodash'
import { goodsLocationEnable } from '../../../api/wms'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const props = defineProps(['visible', 'title', 'orderId'])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const productPopoverRef = ref()
const productRef = ref()
const batchPopoverRef = ref()
const batchRef = ref()
const formRefs = ref([])
//表单相关
const formInfo = reactive({
  data: {},
  fieldList: [
    {
      label: '任务单号',
      value: 'orderNo',
    },
    {
      label: '耗材品类数',
      value: 'productQty',
    },
    {
      label: '耗材总数量',
      value: 'totalQty',
    },
    {
      label: '接单时间',
      value: 'receivingTime',
    },
    {
      label: '完成时间',
      value: 'completeTime',
    },
    {
      label: '状态',
      value: 'statusValue',
    },
    {
      label: '仓库',
      value: 'depotName',
    },
    {
      label: '捡货人',
      value: 'downSelfUserName',
    },
    {
      label: '创建人',
      value: 'createUserName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      pendDownSelfCalcQtyGt: 0,
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  sysGroup: [],
  productSysGroup: [],
  data: [
    {
      emptyRowType: '1', //1添加产品和批次，2添加批次
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    },
  ],
  tabList: [],
  tabIndex: 0,
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    // { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    // {
    //   label: '通用名称',
    //   value: 'commonName',
    //   type: 'slot',
    //   minWidth: '100px',
    // },
    // {
    //   label: '产品编码',
    //   value: 'productCode',
    //   width: '100px',
    // },
    // {
    //   label: '规格',
    //   value: 'standard',
    // },
    // {
    //   label: '厂家',
    //   value: 'brandName',
    //   width: '80px',
    // },
    // {
    //   label: '单位',
    //   value: 'unitName',
    //   width: '80px',
    // },
    // /*   {
    //     label: '条码类型',
    //     value: 'codeTypeValue',
    //   }, */
    // {
    //   label: '批号',
    //   value: 'batchNumber',
    // },
    // {
    //   label: '生产日期',
    //   value: 'productionDate',
    //   width: '80px',
    // },
    // {
    //   label: '失效日期',
    //   value: 'validityDate',
    //   width: '80px',
    // },
    // {
    //   label: '供应商',
    //   value: 'supplierName',
    // },
    // {
    //   label: '单价',
    //   value: 'price',
    //   type: 'column',
    //   formatter: proxy.$fn.TripartiteMethod,
    //   permission: !proxy.$permission('downShelfTask:price'),
    //   width: '60px',
    // },
    // {
    //   label: '可拣数',//待拣货数量，downSelfQty拣货总数
    //   value: 'pendDownSelfQty',
    //   type: 'column',
    //   formatter: proxy.$fn.qtyFormatter,
    //   width: '60px',
    // },
    // {
    //   label: '入库批次号',
    //   value: 'storeBatchNumber',
    //   type: 'slot',
    //   minWidth: '100px',
    // },
    // {
    //   label: '货位号',
    //   align: 'left',
    //   value: 'goodsLocationNo',
    //   type: 'slot',
    //   minWidth: '100px',
    // },
    // {
    //   label: '可用数',
    //   value: 'stockAvailableQty',
    //   type: 'column',
    //   formatter: proxy.$fn.qtyFormatter,
    //   width: '60px',
    // },
    // {
    //   label: '拣货数量',
    //   value: 'qty',
    //   type: 'slot',
    // },
    // {
    //   label: '拣货金额',
    //   value: 'sumAmount',
    //   type: 'column',
    //   formatter: proxy.$fn.TripartiteMethod,
    //   permission: !proxy.$permission('downShelfTask:price'),
    //   width: '80px',
    // },
  ],
  handle: {
    fixed: 'right',
    label: '批次操作',
    width: '100',
    btList: [
      {
        label: '个体详情',
        event: individualDetails,
        show: true,
        ifRender: ifRenderIndividual,
      },
      {
        label: '新增',
        event: addBucth,
        show: true,
        ifRender: ifRenderAddButch,
      },
      {
        label: '删除',
        event: removeBatch,
        show: true,
        ifRender: function (row) {
          return !row.emptyRowType
        },
      },
    ],
  },
  bigWidth: {
    productCode: '100px',
    standard: '60px',
    brandName: '80px',
    unitName: '80px',
    batchNumber: '100px',
    productionDate: '80px',
    validityDate: '80px',
    supplierName: '80px',
    price: '80px',
    stockAvailableQty: '60px',
    qty: '140px',
    sumAmount: '80px',
  },
  smallWidth: {
    productCode: '90px',
    standard: '60px',
    brandName: '60px',
    unitName: '40px',
    batchNumber: '60px',
    productionDate: '50px',
    validityDate: '80px',
    supplierName: '60px',
    price: '50px',
    stockAvailableQty: '50px',
    qty: '90px',
    sumAmount: '70px',
  },
})
const selectProductInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  api: getDownShelfTaskDetailCustomizeListPage,
  query: {
    excludeQueryList: [],
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.orderId || '',
      },
    },
    queryParams: {
      isShelfSearchLeft: 1,
      stockSearchKey: '',
    },
  },
  tableKey:
    'wmsDownShelfTaskAddProduct-com.slip.spd.entity.vo.wms.WmsDownShelfTaskDetailVO',
  highlightRow: true,
  checkBox: false,
})
const selectBatchInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  api: getDepotStockCustomizeListPage,
  row: {},
  index: 0,
  query: {
    excludeQueryList: [],
    queryMap: {
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      },
      productionDate: {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      },
      validityDate: {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'IN',
        value: null,
      },
      storeBatchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
    },
    queryParams: {
      isShelfSearchRight: 1,
      locationNoSearch: '',
      groupField: '',
    },
  },
  tableKey:
    'wmsDownShelfTaskAddGoodsLocationNo-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  highlightRow: true,
  checkBox: false,
})

const individualInfo = ref({
  visible: false,
  isRequest: false,
  row: {},
  details: [],
  rightVo: {},
  index: '',
  leftQuery: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      price: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      storeBatchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
    },
    queryParams: {
      isShelfSearchRight: 1,
      groupField: '',
    },
  }, //个体弹窗左边数据查询条件
  rightQuery: {
    queryMap: {
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.orderId || '',
      },
    },
    queryParams: {},
  }, //个体弹窗右边数据查询条件
  leftTableKey:
    'wmsDownShelfTaskIndividualLeft-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  rightTableKey:
    'wmsDownShelfTaskIndividualRight-com.slip.spd.entity.vo.wms.WmsDownShelfTaskDetailExtVO',
  rightApi: getDownShelfTaskDetailExtCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
})
let disStartDate = ref('')
let disEndDate = ref('')
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      let list = []
      tableInfo.value.data.forEach((item, index) => {
        if (item.emptyRowType && item.emptyRowType === '1') {
          let arr = [
            { key: 'productKey' + index, index: index },
            { key: 'batchKey' + index, index: index },
          ]
          list = list.concat(arr)
        } else if (item.emptyRowType && item.emptyRowType === '2') {
          list.push({ key: 'batchKey' + index, index: index })
        }
        let cargoStockIds = []
        if (item.details && item.details.length) {
          cargoStockIds = item.details.map((el) => el.cargoStockId)
        } else {
          if (item.groupConcatCargoStockIds) {
            cargoStockIds.push(item.groupConcatCargoStockIds)
          }
        }
        item.groupConcatCargoStockIds = cargoStockIds.length
          ? cargoStockIds.toString()
          : ''
      })

      tableInfo.value.tabList = list
      setTabindex(proxy)
      setSuplierIdMap()
    }
  },
  { deep: true }
)

watch(
  () => selectBatchInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectProductInfo.value.popoVisible = false
    }
  }
)
watch(
  () => selectProductInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectBatchInfo.value.popoVisible = false
    }
  }
)

window.addEventListener('click', closePopper, { passive: true })
window.addEventListener('keydown', addTab, true)
onActivated(() => {
  window.addEventListener('click', closePopper, { passive: true })
  window.addEventListener('keydown', addTab, true)
})
onDeactivated(() => {
  window.removeEventListener('click', closePopper, true)
  window.removeEventListener('keydown', addTab, true)
})
function addTab(val) {
  if (val.key === 'Tab') {
  }
}
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
function closePopper(e) {
  if (
    e.target.closest('.el-popper') ||
    e.target.closest('.productKey') ||
    e.target.closest('.batchKey')
  ) {
    // 点击当前元素处理操作
  } else {
    //点击非当前元素，需要执行的代码
    selectBatchInfo.value.popoVisible = false
    selectProductInfo.value.popoVisible = false
  }
}
const canSave = computed(() => {
  return tableInfo.value.data.length
})

const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.fieldList = formInfo.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
  proxy.$fn.setFieldListColWidth(
    tableInfo.value.fieldList,
    tableInfo.value.bigWidth,
    tableInfo.value.smallWidth
  )
})
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let len = tableInfo.value.fieldList.length
  if (row.emptyRowType !== '1' || !row.emptyRowType) {
    let afterIndexs = row.codeType === 2 || row.codeType === 3 ? [len + 1] : []
    let keys = new Array(len + 2)
    if (afterIndexs.length && afterIndexs.includes(columnIndex)) {
      keys[columnIndex] = 'groupKey'
    } else {
      keys = [
        'groupKey',
        'commonName',
        'productCode',
        'standard',
        'brandName',
        'unitName',
        'batchNumber',
        'productionDate',
        'validityDate',
        'supplierName',
        'pendDownSelfQty',
        'storeBatchNumber',
      ]
      if (proxy.$permission('downShelfTask:price')) {
        keys = [
          'groupKey',
          'commonName',
          'productCode',
          'standard',
          'brandName',
          'unitName',
          'batchNumber',
          'productionDate',
          'validityDate',
          'supplierName',
          'price',
          'pendDownSelfQty',
          'storeBatchNumber',
        ]
      }
    }
    // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
    return proxy.$fn.spanMethod(
      tableInfo.value.data,
      keys,
      rowIndex,
      columnIndex
    )
  }
}
function ifRenderAddButch(row) {
  let arr = [1, 4]
  if (arr.includes(row.codeType)) {
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === row.groupKey
    )
    let index = list.findIndex((item) => item._key === row._key)
    return index === list.length - 1
  }
}
function ifRenderIndividual(row) {
  let arr = [2, 3]
  return arr.includes(row.codeType) && row.emptyRowType !== '1'
}
//新增行
function addProduct() {
  tableInfo.value.data.push({
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  })
}
function checkMore(str) {
  if (str === 'product') {
    let row = selectProductInfo.value.row
    let index = selectProductInfo.value.index
    productSearch(row, index)
  } else if (str === 'batch') {
    let row = selectBatchInfo.value.row
    let index = selectBatchInfo.value.index
    batchNumberSearch(row, index)
  }
}
function productSearch(row, index) {
  //产品点击查询图标
  selectProductInfo.value.query.queryParams.stockSearchKey = row.productKeyword
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  let key = []
  tableInfo.value.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === '2') {
      let arr = []
      tableInfo.value.productSysGroup.forEach((item) => {
        let obj = {}
        obj.columnName = item.columnName
        obj.asTbName = item.asTbName
        obj.value = row[item.key]
        arr.push(obj)
      })
      key.push(arr)
    }
  })
  selectProductInfo.value.query.excludeQueryList = key
  selectProductInfo.value.visible = true
  selectProductInfo.value.popoVisible = false
}

function productSearchInput(row, index) {
  //产品enter查询

  let key = []
  tableInfo.value.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === '2') {
      let arr = []
      tableInfo.value.productSysGroup.forEach((item) => {
        let obj = {}
        obj.columnName = item.columnName
        obj.asTbName = item.asTbName
        obj.value = row[item.key]
        arr.push(obj)
      })
      key.push(arr)
    }
  })
  productRef.value = proxy.$refs['productRef' + index]
  selectProductInfo.value.query.excludeQueryList = key
  selectProductInfo.value.query.queryParams.stockSearchKey = row.productKeyword
  selectProductInfo.value.refresh = Math.random()
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  selectProductInfo.value.popoVisible = true
}
function productKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'productKey' + selectProductInfo.value.index
      setVal(className)
      selectProductInfo.value.popoVisible = false
      return
    }
    let className = 'productKey' + selectProductInfo.value.index
    let productKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    productKeyDom.blur()
  })
}
function selectProductBack(obj) {
  let index = selectProductInfo.value.index
  tableInfo.value.data[index] = {
    commonName: obj.commonName,
    productCode: obj.productCode,
    groupKey: obj.groupKey,
    standard: obj.standard,
    brandName: obj.brandName,
    brandId: obj.brandId,
    unitName: obj.unitName,
    unitId: obj.unitId,
    codeTypeValue: obj.codeTypeValue,
    codeType: obj.codeType,
    batchNumber: obj.batchNumber,
    productionDate: obj.productionDate,
    validityDate: obj.validityDate,
    orgId: obj.orgId,
    id: obj.id,
    productId: obj.productId,
    supplierName: obj.supplierName,
    supplierId: obj.supplierId,
    price: obj.price,
    pendDownSelfQty: obj.pendDownSelfQty,
    cargoStockId: obj.cargoStockId,
    pendDownSelfCalcQty: obj.pendDownSelfCalcQty,
    storeBatchNumber: obj.storeBatchNumber,
    emptyRowType: '2',
  }
  // if (obj.codeType === 1 || obj.codeType === 4) {
  //   batchNumberSearchInput(tableInfo.value.data[index], index)
  // } else if (obj.codeType === 2 || obj.codeType === 3) {
  //   batchNumberSearch(tableInfo.value.data[index], index)
  // }

  let itemList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  )
  if (!itemList.length) {
    tableInfo.value.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
function selectProductBackList(data) {
  let index = selectProductInfo.value.index
  let newData = data.map((item) => {
    return {
      commonName: item.commonName,
      productCode: item.productCode,
      groupKey: item.groupKey,
      standard: item.standard,
      brandName: item.brandName,
      brandId: item.brandId,
      unitName: item.unitName,
      unitId: item.unitId,
      codeTypeValue: item.codeTypeValue,
      codeType: item.codeType,
      batchNumber: item.batchNumber,
      productionDate: item.productionDate,
      validityDate: item.validityDate,
      productId: item.productId,
      orgId: item.orgId,
      id: item.id,
      supplierName: item.supplierName,
      supplierId: item.supplierId,
      price: item.price,
      pendDownSelfQty: item.pendDownSelfQty,
      cargoStockId: item.cargoStockId,
      pendDownSelfCalcQty: item.pendDownSelfCalcQty,
      storeBatchNumber: item.storeBatchNumber,
      emptyRowType: '2',
    }
  })
  let emptyRowTypeList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  ) //空行条数
  let list = proxy.$fn.deepClone(tableInfo.value.data)
  let leftList,
    rightList = []
  if (emptyRowTypeList.length > 1) {
    if (index === tableInfo.value.data.length - 1) {
      //是否最后一条
      leftList = list.slice(0, index)
      rightList = list.slice(index)
    } else {
      leftList = list.slice(0, index)
      rightList = list.slice(index + 1)
    }
  } else {
    leftList = list.slice(0, index)
    rightList = list.slice(index)
  }
  tableInfo.value.data = leftList.concat(newData).concat(rightList)
  console.log(tableInfo.value.data)
}
function productPopoHide() {
  selectProductInfo.value.popoVisible = false
}
function batchNumberSearch(row, index) {
  //批次点击查询图标
  if (!row.groupKey) return
  selectBatchInfo.value.query.queryParams.locationNoSearch = row.batchKeyword
  selectBatchInfo.value.row = row
  selectBatchInfo.value.index = index
  let list = tableInfo.value.data.filter(
    (item) => item.groupKey === row.groupKey
  )
  let ids = []
  if (list.length) {
    list.forEach((row) => {
      if (row.groupConcatCargoStockIds) {
        ids.push(row.groupConcatCargoStockIds)
      }
    })
  }
  selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
  selectBatchInfo.value.query.queryMap.productId.value = row.productId
  selectBatchInfo.value.query.queryMap.storeBatchNumber.value = row.storeBatchNumber
  selectBatchInfo.value.query.queryMap.isConsignBusiness.value =
    formInfo.data.isConsignBusiness
  if (row.batchNumber) {
    selectBatchInfo.value.query.queryMap.batchNumber = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.batchNumber,
    }
  } else {
    selectBatchInfo.value.query.queryMap.batchNumber = {
      queryType: 'NULL',
      queryCategory: 'AND',
      value: '',
    }
  }
  if (row.validityDate) {
    selectBatchInfo.value.query.queryMap.validityDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.validityDate,
    }
  } else {
    selectBatchInfo.value.query.queryMap.validityDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.productionDate) {
    selectBatchInfo.value.query.queryMap.productionDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.productionDate,
    }
  } else {
    selectBatchInfo.value.query.queryMap.productionDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  // selectBatchInfo.value.query.queryMap.batchNumber.value = row.batchNumber || ''
  // selectBatchInfo.value.query.queryMap.validityDate.value =
  //   row.validityDate || ''
  // selectBatchInfo.value.query.queryMap.productionDate.value =
  //   row.productionDate || ''
  selectBatchInfo.value.query.queryMap.id.value = ids.length
    ? ids.toString()
    : ''
  selectBatchInfo.value.visible = true
  selectBatchInfo.value.popoVisible = false
}
function batchNumberSearchInput(row, index) {
  //批次enter查询
  let timer = setTimeout(() => {
    if (!row.groupKey) return
    let className = 'batchKey' + index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.focus()
    batchRef.value = proxy.$refs['batchRef' + index]
    selectBatchInfo.value.query.queryParams.locationNoSearch = row.batchKeyword
    selectBatchInfo.value.refresh = Math.random()
    selectBatchInfo.value.row = row
    selectBatchInfo.value.index = index
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === row.groupKey
    )
    let ids = []
    if (list.length) {
      list.forEach((row) => {
        if (row.groupConcatCargoStockIds) {
          ids.push(item.groupConcatCargoStockIds)
        }
      })
    }

    selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
    selectBatchInfo.value.query.queryMap.productId.value = row.productId
    if (row.batchNumber) {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.batchNumber,
      }
    } else {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: 'NULL',
        queryCategory: 'AND',
        value: '',
      }
    }
    if (row.validityDate) {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.validityDate,
      }
    } else {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      }
    }
    if (row.productionDate) {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.productionDate,
      }
    } else {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      }
    }
    selectBatchInfo.value.query.queryMap.id.value = ids.length
      ? ids.toString()
      : ''
    selectBatchInfo.value.popoVisible = true
    clearTimeout(timer)
  }, 0)
}
function batchPopoHide() {
  selectBatchInfo.value.popoVisible = false
}
function selectBatchBack(obj) {
  let index = selectBatchInfo.value.index
  let data = proxy.$fn.deepClone(tableInfo.value.data[index])
  obj.cargoStockId = obj.id
  obj.goodsLocationNo = obj.locationNo
  obj = countData(obj)
  obj.pendDownSelfQty = selectBatchInfo.value.row.pendDownSelfQty || 0
  obj.pendDownSelfCalcQty = selectBatchInfo.value.row.pendDownSelfCalcQty || 0
  obj.id = selectBatchInfo.value.row.id
  obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
  obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
  tableInfo.value.data[index] = proxy.$fn.deepClone(obj)
  tableInfo.value.data[index].details = [proxy.$fn.deepClone(obj)]
  tableInfo.value.data[index].groupKey = data.groupKey
}
function selectBatchBackList(data) {
  let row = selectBatchInfo.value.row
  let index = selectBatchInfo.value.index
  console.log(selectBatchInfo.value.row)
  data.forEach((item) => {
    item.cargoStockId = item.id
    item.goodsLocationNo = item.locationNo
    item = countData(item)
  })
  console.log(data)
  let groupData = _.groupBy(data, '_key')
  let groupKeys = Object.keys(groupData)
  let groupKeysIn = []
  tableInfo.value.data.forEach((item) => {
    if (item.groupKey === row.groupKey) {
      if (item._key) {
        if (groupKeys.includes(item._key)) {
          groupKeysIn.push(item._key)
          item.details = item.details.concat(groupData[item._key])
          item = countQty(item)
        }
      }
    }
  })
  let list = []
  if (groupKeysIn.length) {
    groupKeys.forEach((item) => {
      if (!groupKeysIn.includes(item)) {
        let groupDataItem = groupData[item]
        let obj = proxy.$fn.deepClone(groupDataItem[0])
        obj.details = proxy.$fn.deepClone(groupDataItem)
        obj.groupKey = row.groupKey
        obj = countQty(obj)
        obj.pendDownSelfQty = selectBatchInfo.value.row.pendDownSelfQty || 0
        obj.pendDownSelfCalcQty =
          selectBatchInfo.value.row.pendDownSelfCalcQty || 0
        obj.id = selectBatchInfo.value.row.id
        obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
        obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
        list.push(obj)
      }
    })
  } else {
    let values = Object.values(groupData)
    values.forEach((item) => {
      let obj = proxy.$fn.deepClone(item[0])
      obj.details = proxy.$fn.deepClone(item)
      obj.groupKey = row.groupKey
      obj = countQty(obj)
      obj.pendDownSelfQty = selectBatchInfo.value.row.pendDownSelfQty || 0
      obj.pendDownSelfCalcQty =
        selectBatchInfo.value.row.pendDownSelfCalcQty || 0
      obj.id = selectBatchInfo.value.row.id
      obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
      obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
      list.push(obj)
    })
  }
  if (list.length) {
    let newData = tableInfo.value.data[index]
    let leftList = []
    if (newData._key) {
      leftList = tableInfo.value.data.slice(0, index + 1)
    } else {
      leftList = tableInfo.value.data.slice(0, index)
    }
    let rightList = tableInfo.value.data.slice(index + 1)
    tableInfo.value.data = leftList.concat(list).concat(rightList)
  }
  console.log(tableInfo.value.data)
}
function countQty(data) {
  let largeUnitQty = 0
  let smallUnitQty = 0
  let calcQty = 0
  if (data.details && data.details.length) {
    data.details.forEach((el) => {
      largeUnitQty = proxy.$fn.accAdd(largeUnitQty, el.largeUnitQty || 0)
      smallUnitQty = proxy.$fn.accAdd(smallUnitQty, el.smallUnitQty || 0)
      calcQty = proxy.$fn.accAdd(calcQty, el.calcQty || 0)
    })
  }
  data.largeUnitQty = largeUnitQty
  data.smallUnitQty = smallUnitQty
  data.calcQty = calcQty
  data.qty = proxy.$fn.accDiv(calcQty, data.unitConvertCoefficient || 1)
  data.sumAmount = proxy.$fn.accDiv(
    proxy.$fn.accMul(calcQty, data.price || 0),
    data.unitConvertCoefficient || 1
  )
  return data
}
function batchKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'batchKey' + selectProductInfo.value.index
      setVal(className)
      selectBatchInfo.value.popoVisible = false
      return
    }
    let className = 'batchKey' + selectBatchInfo.value.index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.blur()
  })
}

function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }

  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
  }
}
function changeSmall(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(row.calcQty || 0, parseFloat(row.price || 0)),
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
    row.details[0].sumAmount = row.sumAmount
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function countData(data) {
  if (data.stockAvailableCalcQty > data.unitConvertCoefficient) {
    data.calcQty = data.unitConvertCoefficient
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
    data.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(data.calcQty, data.price),
      data.unitConvertCoefficient
    )
  } else {
    data.calcQty = data.stockAvailableCalcQty
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
    data.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(data.calcQty, data.price),
      data.unitConvertCoefficient
    )
  }
  data._key = data.goodsLocationId + '&' + data.productId
  groupKeyMap.value[data.supplierId] = 1

  return data
}
function tableCellClassName({ column, row }) {
  if (row.isChoice && column.property === 'qty') {
    return 'success-row'
  } else {
    return ''
  }
}
function addBucth(row, index) {
  batchNumberSearch(row, index)
}
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let groupKeys = tableInfo.value.selections.map((item) => item.groupKey)
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => !groupKeys.includes(item.groupKey)
      )
      if (!tableInfo.value.data.length) {
        tableInfo.value.data = [
          {
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          },
        ]
      } else {
        let index = tableInfo.value.data.findIndex(
          (item) => item.emptyRowType === '1'
        )
        if (index === -1) {
          tableInfo.value.data.push({
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          })
        }
      }
      const data = proxy.$fn.deepClone(tableInfo.value.data)
      tableInfo.value.data = []
      proxy.$nextTick(() => {
        tableInfo.value.data = data
      })
    })
}
// 用于存储groupKey对应批次数量
const groupKeyMap = ref({})
function setSuplierIdMap() {
  let _data = tableInfo.value.data.filter((element) => {
    return element.groupKey
  })
  groupKeyMap.value = _.groupBy(_data, 'groupKey')
}
function removeBatch(row, index) {
  if (row.codeType === 1 || row.codeType === 4) {
    if (
      groupKeyMap.value[row.groupKey] &&
      groupKeyMap.value[row.groupKey]?.length > 1
    ) {
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => ![row].includes(item)
      )
    } else {
      tableInfo.value.data[index] = {
        commonName: row.commonName,
        productCode: row.productCode,
        groupKey: row.groupKey,
        standard: row.standard,
        brandName: row.brandName,
        brandId: row.brandId,
        unitName: row.unitName,
        unitId: row.unitId,
        codeTypeValue: row.codeTypeValue,
        codeType: row.codeType,
        batchNumber: row.batchNumber,
        productionDate: row.productionDate,
        validityDate: row.validityDate,
        productId: row.productId,
        orgId: row.orgId,
        id: row.id,
        supplierName: row.supplierName,
        supplierId: row.supplierId,
        price: row.price,
        pendDownSelfQty: row.pendDownSelfQty,
        cargoStockId: row.cargoStockId,
        pendDownSelfCalcQty: row.pendDownSelfCalcQty,
        storeBatchNumber: row.storeBatchNumber,
        emptyRowType: '2',
      }
    }
  } else if (row.codeType === 2 || row.codeType === 3) {
    tableInfo.value.data[index] = {
      commonName: row.commonName,
      productCode: row.productCode,
      groupKey: row.groupKey,
      standard: row.standard,
      brandName: row.brandName,
      brandId: row.brandId,
      unitName: row.unitName,
      unitId: row.unitId,
      codeTypeValue: row.codeTypeValue,
      codeType: row.codeType,
      batchNumber: row.batchNumber,
      productionDate: row.productionDate,
      validityDate: row.validityDate,
      productId: row.productId,
      orgId: row.orgId,
      id: row.id,
      supplierName: row.supplierName,
      supplierId: row.supplierId,
      price: row.price,
      pendDownSelfQty: row.pendDownSelfQty,
      cargoStockId: row.cargoStockId,
      pendDownSelfCalcQty: row.pendDownSelfCalcQty,
      storeBatchNumber: row.storeBatchNumber,
      emptyRowType: '2',
    }
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === row.groupKey
    )
    tableInfo.value.data = tableInfo.value.data.filter((item, i) => {
      if (!list.includes(item) || index === i) {
        return item
      }
    })
  }
}
function individualDetails(row, index) {
  let list = tableInfo.value.data.filter(
    (item) => item.groupKey === row.groupKey
  )
  let details = []
  let isRequest = false
  let cargoStockIds = []
  let groupConcatId = []
  if (list.length) {
    list.forEach((item) => {
      if (item.details && item.details.length) {
        details = details.concat(item.details)
      }
      if (
        !item.details &&
        item.groupConcatIds &&
        item.groupConcatCargoStockIds
      ) {
        isRequest = true
      }
      if (item.groupConcatIds) {
        groupConcatId.push(item.groupConcatIds)
      }
      if (item.groupConcatCargoStockIds) {
        cargoStockIds.push(item.groupConcatCargoStockIds)
      }
    })
  }
  individualInfo.value.row = row
  individualInfo.value.details = details
  individualInfo.value.index = index
  individualInfo.value.leftQuery.queryMap.orgId.value = row.orgId
  individualInfo.value.leftQuery.queryMap.productId.value = row.productId
  individualInfo.value.leftQuery.queryMap.price.value = row.price
  individualInfo.value.leftQuery.queryMap.storeBatchNumber.value =
    row.storeBatchNumber
  if (row.batchNumber) {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.batchNumber,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'NULL',
      queryCategory: 'AND',
      value: '',
    }
  }
  if (row.validityDate) {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.validityDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.productionDate) {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.productionDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.supplierId) {
    individualInfo.value.leftQuery.queryMap.supplierId = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.supplierId,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.supplierId = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  individualInfo.value.leftQuery.queryMap.id.value = cargoStockIds.length
    ? cargoStockIds.toString()
    : ''

  individualInfo.value.isRequest = isRequest
  individualInfo.value.visible = true
}
function individualCallback(data) {
  let index = individualInfo.value.index
  let row = individualInfo.value.row
  if (data.length) {
    data.forEach((item) => {
      item._key = item.goodsLocationId + '&' + item.productId
      item.goodsLocationNo = item.locationNo
    })
    let groupData = _.groupBy(data, '_key')
    let groupKeys = Object.keys(groupData)
    let groupKeysIn = []
    tableInfo.value.data = tableInfo.value.data.filter((item) => {
      if (item.groupKey === row.groupKey) {
        if (item._key) {
          return groupKeys.includes(item._key)
        } else {
          return item
        }
      } else {
        return item
      }
    })
    console.log(tableInfo.value.data)
    tableInfo.value.data.forEach((item) => {
      if (item.groupKey === row.groupKey) {
        if (item._key) {
          if (groupKeys.includes(item._key)) {
            groupKeysIn.push(item._key)
            item.details = groupData[item._key]
            item = countQty(item)
          }
        }
      }
    })
    let list = []
    if (groupKeysIn.length) {
      groupKeys.forEach((item) => {
        if (!groupKeysIn.includes(item)) {
          let groupDataItem = groupData[item]
          let obj = proxy.$fn.deepClone(groupDataItem[0])
          obj.details = proxy.$fn.deepClone(groupDataItem)
          obj.groupKey = row.groupKey
          obj = countQty(obj)
          obj.pendDownSelfQty = individualInfo.value.row.pendDownSelfQty || 0
          obj.pendDownSelfCalcQty =
            individualInfo.value.row.pendDownSelfCalcQty || 0
          obj.id = individualInfo.value.row.id
          obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
          obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
          list.push(obj)
        }
      })
    } else {
      let values = Object.values(groupData)
      values.forEach((item) => {
        let obj = proxy.$fn.deepClone(item[0])
        obj.details = proxy.$fn.deepClone(item)
        obj.groupKey = row.groupKey
        obj = countQty(obj)
        obj.pendDownSelfQty = individualInfo.value.row.pendDownSelfQty || 0
        obj.pendDownSelfCalcQty =
          individualInfo.value.row.pendDownSelfCalcQty || 0
        obj.id = individualInfo.value.row.id
        obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
        obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
        list.push(obj)
      })
    }
    if (list.length) {
      let newData = tableInfo.value.data[index]
      let leftList = []
      if (newData._key) {
        leftList = tableInfo.value.data.slice(0, index + 1)
      } else {
        leftList = tableInfo.value.data.slice(0, index)
      }
      let rightList = tableInfo.value.data.slice(index + 1)
      tableInfo.value.data = leftList.concat(list).concat(rightList)
    }
  } else {
    tableInfo.value.data[index] = {
      commonName: row.commonName,
      productCode: row.productCode,
      groupKey: row.groupKey,
      standard: row.standard,
      brandName: row.brandName,
      brandId: row.brandId,
      unitName: row.unitName,
      unitId: row.unitId,
      codeTypeValue: row.codeTypeValue,
      codeType: row.codeType,
      batchNumber: row.batchNumber,
      productionDate: row.productionDate,
      validityDate: row.validityDate,
      productId: row.productId,
      orgId: row.orgId,
      id: row.id,
      supplierName: row.supplierName,
      supplierId: row.supplierId,
      price: row.price,
      pendDownSelfQty: row.pendDownSelfQty,
      cargoStockId: row.cargoStockId,
      pendDownSelfCalcQty: row.pendDownSelfCalcQty,
      storeBatchNumber: row.storeBatchNumber,
      emptyRowType: '2',
    }
    tableInfo.value.data = tableInfo.value.data.filter((item) => {
      if (row.groupKey === item.groupKey) {
        return item.emptyRowType === '2'
      } else {
        return item
      }
    })
  }
  let emptyIndex = tableInfo.value.data.findIndex(
    (item) => item.emptyRowType === '1'
  )
  if (emptyIndex === -1) {
    tableInfo.value.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}

function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetailsList = tableInfo.value.data.filter(
      (row) => row.productId && row.calcQty > 0
    )
    if (!newDetailsList.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let emptyDetails = newDetailsList
      .filter((item) => item.emptyRowType === '2')
      .map((item) => item.commonName)
    if (emptyDetails.length) {
      proxy.$message({
        message: '请添产品【' + emptyDetails + '】的批次信息',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let commonNames = []
    let groupData = _.groupBy(newDetailsList, 'groupKey')
    let groupDataValues = Object.values(groupData)
    groupDataValues.forEach((item) => {
      let calcQty = 0
      item.forEach((el) => {
        calcQty = proxy.$fn.accAdd(el.calcQty || 0, calcQty)
      })
      if (calcQty > item[0].pendDownSelfCalcQty) {
        commonNames.push(item[0].commonName)
      }
    })
    console.log(commonNames)
    if (commonNames.length) {
      proxy.$message({
        message: `产品【${commonNames}】的拣货数量不能大于可拣数，请修改`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let newDetails = newDetailsList.filter((item) => item.calcQty > 0)
    const data = formInfo.data
    data.mergeDetails = newDetails
    downShelfSave(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify', false)
      }
    })
  })
}

function getMain() {
  getDownShelfById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      filterInfo.query.queryMap.orderId.value = props.orderId
      selectBatchInfo.value.query.queryMap.depotId.value = resp.data.depotId
      individualInfo.value.leftQuery.queryMap.depotId.value = resp.data.depotId
      individualInfo.value.rightQuery.queryMap.depotId.value = resp.data.depotId
      getList()
      setBusinessDate()
    }
  })
}
function getList() {
  //修改请求明细信息
  getDownShelfTaskDetailCustomizeListAll(filterInfo.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data
      let arr = []
      data.forEach((row) => {
        let str = ''
        tableInfo.value.sysGroup.forEach((item) => {
          if (item === 'productionDate' || item === 'validityDate') {
            str = str + (row[item] || '1900-01-01') + ''
          } else {
            str = str + row[item] + ''
          }
        })
        if (
          (row.codeType === 1 || row.codeType === 4) &&
          row.calcQty > row.stockAvailableCalcQty
        ) {
          row.calcQty = proxy.$fn.deepClone(row.stockAvailableCalcQty)
          let unitConvertCoefficient = row.unitConvertCoefficient || 1
          row.qty = proxy.$fn.accDiv(row.calcQty, unitConvertCoefficient)
          row.largeUnitQty = parseInt(row.calcQty / unitConvertCoefficient)
          row.smallUnitQty = parseInt(row.calcQty % unitConvertCoefficient)
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(row.calcQty, row.price || 0),
            unitConvertCoefficient
          )
        }
        row.groupKey = str
        row._key = row.goodsLocationId + '&' + row.productId

        arr.push({
          commonName: row.commonName,
          productCode: row.productCode,
          groupKey: row.groupKey,
          standard: row.standard,
          brandName: row.brandName,
          brandId: row.brandId,
          unitName: row.unitName,
          unitId: row.unitId,
          codeTypeValue: row.codeTypeValue,
          codeType: row.codeType,
          batchNumber: row.batchNumber,
          productionDate: row.productionDate,
          validityDate: row.validityDate,
          productId: row.productId,
          orgId: row.orgId,
          id: row.id,
          supplierName: row.supplierName,
          supplierId: row.supplierId,
          price: row.price,
          pendDownSelfQty: row.pendDownSelfQty,
          cargoStockId: row.cargoStockId,
          pendDownSelfCalcQty: row.pendDownSelfCalcQty,
          storeBatchNumber: row.storeBatchNumber,
          emptyRowType: '2',
        })
      })
      tableInfo.value.data = arr
      tableInfo.value.data.push({
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      })
      console.log(tableInfo.value.data)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'wmsDownShelfTaskProductBatchModify-com.slip.spd.entity.vo.wms.WmsDownShelfTaskDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      tableInfo.value.fieldList = fieldList.filter((item) => {
        return item.showLevel > 0
      })
      console.log(tableInfo.value.fieldList)
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({ key, sysGroupLevel: data.detail[key].sysGroupLevel })
        }
      }
      arr = proxy.$fn.getSort(arr, 'sysGroupLevel')
      arr = arr.map((element) => {
        return element.key
      })

      selectBatchInfo.value.query.queryParams.groupField = arr.length
        ? arr.toString() + ',goodsLocationId'
        : ''
      individualInfo.value.leftQuery.queryParams.groupField = arr.length
        ? arr.toString() + ',goodsLocationId'
        : ''
      tableInfo.value.sysGroup = arr
      if (props.orderId) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getProductCustomize() {
  let param = {
    tableKey:
      'wmsDownShelfTaskAddProduct-com.slip.spd.entity.vo.wms.WmsDownShelfTaskDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({
            columnName: data.detail[key].columnName,
            asTbName: data.detail[key].asTbName,
            key: key,
          })
        }
      }
      tableInfo.value.productSysGroup = arr
    }
  })
}
function getIndividualRightCustomize() {
  let param = {
    tableKey:
      'stockTransferOrderProductIndividualRight-com.slip.spd.entity.vo.stock.TransferOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      individualInfo.value.rightVo = data
    }
  })
}
let obj = {
  commonName: {
    label: '通用名称',
    value: 'commonName',
    type: 'slot',
    minWidth: '100px',
  },
  price: {
    label: '单价',
    value: 'price',
    componentType: 'price',
    type: 'slot',
    show: false,
    hidden: true,
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('downShelfTask:price'),
    width: '60px',
  },
  storeBatchNumber: {
    label: '入库批次号',
    value: 'storeBatchNumber',
    type: 'slot',
    minWidth: '100px',
  },
  goodsLocationNo: {
    label: '货位号',
    align: 'left',
    value: 'goodsLocationNo',
    type: 'slot',
    minWidth: '100px',
  },
  pendDownSelfQty: {
    label: '待捡货数量',
    value: 'pendDownSelfQty',
    type: 'slot',
    componentType: 'number',
    formatter: proxy.$fn.qtyFormatter,
    show: false,
    hidden: true,
  },
  qty: {
    label: '拣货数量',
    value: 'qty',
    type: 'slot',
  },
}

tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
getProductCustomize()
getIndividualRightCustomize()
</script>
<style lang="scss" scoped>
.el-input-search {
  width: 100%;
  height: 100%;
}
.isShow {
  :deep(.el-scrollbar__wrap) {
    overflow: inherit;
  }
}
.el-popper {
  overflow-y: hidden;
}
</style>
<style>
.el-popper {
  max-height: max-content !important;
}
</style>
